package com.jinlia.show.modules.base.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;

@EnableAsync
@Configuration
public class ExecutorConfig {

    /**
     *
     * @return
     */
    @Bean(name = "scheduledExecutorService")
    public ScheduledExecutorService asyncPromiseExecutor() {

        ThreadFactory threadFactory = new CustomizableThreadFactory("springThread-pool-");
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2,
                threadFactory);
        System.out.println("scheduledExecutorService::" + scheduledExecutorService.toString());
        return scheduledExecutorService;
    }

    /**
     * 自定义线程池:解决
     * @param scheduledExecutorService
     * @return
     */
    @Bean
    public CustomerScheduledExecutorService asyncCustomerPromiseExecutor(ScheduledExecutorService scheduledExecutorService) {
        System.out.println("asyncCustomerPromiseExecutor::" + scheduledExecutorService.toString());
        CustomerScheduledExecutorService customerScheduledExecutorService = new CustomerScheduledExecutorService(scheduledExecutorService);
        return customerScheduledExecutorService;
    }
    public class CustomerScheduledExecutorService {

        private ScheduledExecutorService scheduledExecutorService;

        public CustomerScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) {
            this.scheduledExecutorService = scheduledExecutorService;
        }

        public Future<?> submit(Runnable task) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);//设置子线程共享
            Future<?> submit = scheduledExecutorService.submit(task);
            return submit;
        }
    }

}
